package com.emm.yixun.customer.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import com.emm.yixun.basic.service.*;
import com.emm.yixun.common.model.*;
import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.common.model.enums.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.emm.yixun.common.app.AddContactWayResDto;
import com.emm.yixun.common.app.AddCustomerReqDto;
import com.emm.yixun.common.app.AddCustomerResDto;
import com.emm.yixun.common.app.AddFollowReqDto;
import com.emm.yixun.common.app.AddFollowResDto;
import com.emm.yixun.common.app.DistributionConsultantReqDto;
import com.emm.yixun.common.app.DistributionConsultantResDto;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.app.servletentity.FamilyMemberListReq;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.enums.SalesReportDto;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.utils.MathUtil;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.customer.service.impl.app.manage.AddCustomerManage;
import com.emm.yixun.customer.service.impl.app.manage.AddFollowManage;
import com.emm.yixun.customer.service.impl.app.manage.DistributionConsultantManage;
import com.emm.yixun.customer.service.impl.app.manage.GetCustomerListManage;

@Service("customerServiceFacade")
@WebService(name = "com.emm.yixun.customer.service.CustomerServiceFacade")
public class CustomerServiceFacadeImpl implements CustomerServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private CustomerService service;
	@Autowired
	private AddCustomerManage addCustomerManage;
	@Autowired
	private DistributionConsultantManage distributionConsultantManage;
	@Autowired
	private AddFollowManage addFollowManage;
	@Autowired
	private AreaService areaServiceFacade;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private UserService userServiceFacade;
	@Autowired
	private BusinessRelationService businessRelationService;
	@Autowired
	private ImageService imageService;
	@Autowired
	private DataPermissionService dataPermissionService;
	@Autowired
	private BaseCodeValueService baseCodeValueService;
	@Autowired
	private ActNodeDataService actNodeDataService;
	@Autowired
	private ProjectRoomService projectRoomService;
	@Autowired
	private GetCustomerListManage getCustomerListManage;
	@Autowired
	private ProjectParameterService projectParameterService;
	@Autowired
	private FollowService followService;
	
	public static Map<String, Long> dicMap = new HashMap<String, Long>();

	@Override
	@Transactional
	public AddCustomerResDto addCustomer(AddCustomerReqDto reqDto, User user) throws Exception {
		AddCustomerResDto resDto = new AddCustomerResDto();
		CommonResDTO commonResDto = new CommonResDTO();
		// 验证客户联系手机号码是否重复
		CustomerDto cusDto = new CustomerDto();
		cusDto.setCustomerPhone(reqDto.getCustomerPhone());
		cusDto.setMerchantId(reqDto.getMerchantId());
		cusDto.setProjectId(reqDto.getProjectId());
		List<Customer> cusEntity = service.selectListByDto(cusDto);
		if (cusEntity.size() > 0) {
			resDto.setResult(ResultEnum.FAILURE.getNo());
			resDto.setErrorCode(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getCode());
			resDto.setErrorMsg(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getDesin());
			return resDto;
		}

		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		reqDto.setUserId(user.getId() + "");
		// 4、记录客户信息 cus_tm_customer
		CustomerDto customerDto = addCustomerManage.addCustomer(reqDto);
		if (customerDto == null) {
			// 抛出异常
			throw new Exception("customer");
		}
		resDto.setCustomerId(String.valueOf(customerDto.getId()));
		// 5、记录关注户型、意向房源、意向组团 cus_tr_business_relation
		if (reqDto.getHouseTypeList() != null && reqDto.getHouseTypeList().size() > 0) {
			// 关注户型
			List<String> houseTypeList = reqDto.getHouseTypeList();
			commonResDto = addCustomerManage.addCusHouseTypeFocus(customerDto, houseTypeList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("houseType");
			}
		}

		// 关注组团(楼盘)
		if (reqDto.getPremisesList() != null && !"".equals(reqDto.getPremisesList())) {
			List<String> premisesList = reqDto.getPremisesList();
			commonResDto = addCustomerManage.addCusPremisesFocus(customerDto, premisesList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("premises");
			}
		}

		// 关注房号
		if (reqDto.getRoomList() != null && !"".equals(reqDto.getRoomList())) {
			List<String> roomList = reqDto.getRoomList();
			commonResDto = addCustomerManage.addCusRoomFocus(customerDto, roomList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("room");
			}
		}

		// 6、记录家庭成员 cus_tr_family_member
		// 家庭成员
		if (!"".equals(reqDto.getFamilyMemberList()) && reqDto.getFamilyMemberList() != null) {
			List<FamilyMemberListReq> familyMemberList = reqDto.getFamilyMemberList();
			customerDto.setCreateUserId(user.getId());
			commonResDto = addCustomerManage.addCusFamily(customerDto, familyMemberList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("family");
			}
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	@Override
	@Transactional
	public AddCustomerResDto allAddCustomer(CustomerDto reqDto) throws Exception {
		AddCustomerResDto resDto = new AddCustomerResDto();
		CommonResDTO commonResDto = new CommonResDTO();

		// 验证客户联系手机号码是否重复
		CustomerDto cusDto = new CustomerDto();
		cusDto.setCustomerPhone(reqDto.getCustomerPhone());
		cusDto.setMerchantId(reqDto.getMerchantId());
		cusDto.setProjectId(reqDto.getProjectId());
		List<Customer> cusEntity = service.selectListByDto(cusDto);
		if (cusEntity.size() > 0) {
			throw new Exception("客户联系电话重复");
		}

		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// reqDto.setUserId(user.getId()+"");
		// 4、记录客户信息 cus_tm_customer
		CustomerDto customerDto = addCustomerManage.allAddCustomer(reqDto);
		if (customerDto == null) {
			// 抛出异常
			throw new Exception("客户保存失败");
		}

		// 6、记录家庭成员 cus_tr_family_member
		// 家庭成员
		if (reqDto.getFamilyMemberLists() != null && reqDto.getFamilyMemberLists().size() != 0) {
			List<FamilyMemberListReq> familyMemberList = new ArrayList<FamilyMemberListReq>();
			FamilyMemberListReq addCustomerReqDto = null;
			for (FamilyMemberModel familyMemberModel : reqDto.getFamilyMemberLists()) {
				addCustomerReqDto = new FamilyMemberListReq();
				BeanUtil.convert2T(addCustomerReqDto, familyMemberModel);
				familyMemberList.add(addCustomerReqDto);
			}
			commonResDto = addCustomerManage.addCusFamily(customerDto, familyMemberList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("家庭成员保存失败");
			}
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	@Override
	@Transactional
	public AddCustomerResDto updateCustomer(AddCustomerReqDto reqDto, User user) throws Exception {
		AddCustomerResDto resDto = new AddCustomerResDto();
		CommonResDTO commonResDto = new CommonResDTO();

		// 验证客户联系手机号码是否重复
		CustomerDto cusDto = new CustomerDto();
		cusDto.setCustomerPhone(reqDto.getCustomerPhone());
		cusDto.setMerchantId(reqDto.getMerchantId());
		cusDto.setProjectId(reqDto.getProjectId());
		// List<Customer> cusEntity = service.selectListByDto(cusDto);
		// if(cusEntity.size() > 0){
		// resDto.setResult(ResultEnum.FAILURE.getNo());
		// resDto.setErrorCode(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getCode());
		// resDto.setErrorMsg(XFUNExceptionCode.USER_CUSTOMERPHONEEXIST.getDesin());
		// return resDto;
		// }

		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		reqDto.setUserId(user.getId() + "");
		// 4、记录客户信息 cus_tm_customer
		CustomerDto customerDto = addCustomerManage.updateCustomer(reqDto);
		if (customerDto == null) {
			// 抛出异常
			throw new Exception("customer");
		}
		// 5、记录关注户型、意向房源、意向组团 cus_tr_business_relation
		if (reqDto.getHouseTypeList() != null && !"".equals(reqDto.getHouseTypeList())) {
			// 关注户型
			customerDto.setCreateUserId(user.getId());
			List<String> houseTypeList = reqDto.getHouseTypeList();
			commonResDto = addCustomerManage.addCusHouseTypeFocus(customerDto, houseTypeList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("houseType");
			}
		}

		// 关注组团(楼盘)
		if (reqDto.getPremisesList() != null && !"".equals(reqDto.getPremisesList())) {
			List<String> premisesList = reqDto.getPremisesList();
			commonResDto = addCustomerManage.addCusPremisesFocus(customerDto, premisesList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("premises");
			}
		}

		// 关注房号
		if (reqDto.getRoomList() != null && !"".equals(reqDto.getRoomList())) {
			List<String> roomList = reqDto.getRoomList();
			commonResDto = addCustomerManage.addCusRoomFocus(customerDto, roomList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("room");
			}
		}

		// 6、记录家庭成员 cus_tr_family_member
		// 家庭成员
		if (!"".equals(reqDto.getFamilyMemberList()) && reqDto.getFamilyMemberList() != null) {
			List<FamilyMemberListReq> familyMemberList = reqDto.getFamilyMemberList();
			customerDto.setCreateUserId(user.getId());
			commonResDto = addCustomerManage.addCusFamily(customerDto, familyMemberList);
			if (StringUtils.isNotEmpty(commonResDto.getErrorCode())) {
				// 抛出异常
				throw new Exception("family");
			}
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	@Override
	public Response<CustomerDto> save(CustomerDto dto) {
		Response<CustomerDto> response = new Response<CustomerDto>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			CustomerDto mDto = service.create(dto);
			if (null == mDto) {
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(CustomerDto dto, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				service.update(dto);
				response.success(Integer.valueOf(1));
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			CustomerDto mDto = new CustomerDto();
			mDto.setId(id);
			int count = service.destroy(mDto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Customer> findById(Long id) {
		Response<Customer> response = new Response<Customer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			Customer entity = service.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<CustomerInfo> findInfoByIdCN(Long id) {
		Response<CustomerInfo> response = new Response<CustomerInfo>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			// RoomStatusEnum.getByNo(room.getRoomStatus()).getDes() Info
			Customer entity = service.selectById(id);
			CustomerInfo customerInfo = new CustomerInfo();
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				BaseCodeValueDto bcvDto = new BaseCodeValueDto();
				bcvDto.setMerchantId(entity.getMerchantId());
				bcvDto.setProjectId(entity.getProjectId());
				List<BaseCodeValue> bcvList = baseCodeValueService.selectListFilterDelFlag(bcvDto);
				Map<Long, String> bcvMap = new HashMap<Long, String>();
				if (null != bcvList && bcvList.size() > 0) {
					for (BaseCodeValue bcv : bcvList) {
						bcvMap.put(bcv.getId(), bcv.getCodeName());
					}
				}

				customerInfo = BeanUtil.convert2T(customerInfo, entity);
				Project project = projectService.selectById(customerInfo.getProjectId());
				customerInfo.setProjectName(project.getProjectName());
				customerInfo
						.setSexName(customerInfo.getCustomerSex() != null && !customerInfo.getCustomerSex().equals("")
								? CustomerSexEnum.getByNo(customerInfo.getCustomerSex()).getDes()
								: "");
				customerInfo.setLevelName(
						customerInfo.getIntentionLevel() != null && !customerInfo.getIntentionLevel().equals("")
								? IntentionLevelEnum.getByNo(customerInfo.getIntentionLevel()).getDes()
								: "");
				customerInfo.setStatusName(
						customerInfo.getCustomerStatus() != null && !customerInfo.getCustomerStatus().equals("")
								? CustomerStatusEnum.getByNo(customerInfo.getCustomerStatus()).getDes()
								: "");
				if (StringUtils.isNotBlank(customerInfo.getCustomerOrigin())) {
					customerInfo.setResourceName(bcvMap.get(Long.parseLong(customerInfo.getCustomerOrigin())));
				}
				if (StringUtils.isNotBlank(customerInfo.getRqTheirMotives())) {
					customerInfo.setDongjiName(bcvMap.get(Long.parseLong(customerInfo.getRqTheirMotives())));
				}
				if (StringUtils.isNotEmpty(customerInfo.getRqFocusId())) {
					customerInfo.setZhongdianName(getValue(customerInfo.getRqFocusId(), bcvMap));
				}
				customerInfo
						.setMianji(customerInfo.getRqDemandArea() != null && !customerInfo.getRqDemandArea().equals("")
								? RqDemandAreaEnum.getByNo(customerInfo.getRqDemandArea()).getDes()
								: "");
				if (StringUtils.isNotBlank(customerInfo.getRqDemandFloor())) {
					customerInfo.setLouceng(bcvMap.get(Long.parseLong(customerInfo.getRqDemandFloor())));
				}
				if (StringUtils.isNotBlank(customerInfo.getRqLifeSupport())) {
					customerInfo.setPeitao(getValue(customerInfo.getRqLifeSupport(), bcvMap));
				}
				if (StringUtils.isNotBlank(customerInfo.getRqServicesId())) {
					customerInfo.setShenghuo(getValue(customerInfo.getRqServicesId(), bcvMap));
				}
				customerInfo.setZongjia(
						customerInfo.getRqBudgetSumprice() != null && !customerInfo.getRqBudgetSumprice().equals("")
								? RqBudgetSumPriceEnum.getByNo(customerInfo.getRqBudgetSumprice()).getDes()
								: "");
				customerInfo.setDanjia(
						customerInfo.getRqBudgetPrice() != null && !customerInfo.getRqBudgetPrice().equals("")
								? RqBudgetPriceEnum.getByNo(customerInfo.getRqBudgetPrice()).getDes()
								: "");
				if (StringUtils.isNotBlank(customerInfo.getRqCourtyardFunction())) {
					customerInfo.setGongneng(bcvMap.get(Long.parseLong(customerInfo.getRqCourtyardFunction())));
				}
				if (StringUtils.isNotBlank(customerInfo.getFtContactWay())) {
					customerInfo.setJiechuType(bcvMap.get(Long.parseLong(customerInfo.getFtContactWay())));
				}
				if (StringUtils.isNotBlank(customerInfo.getPeDocumentType())) {
					customerInfo.setZhengjianType(bcvMap.get(Long.parseLong(customerInfo.getPeDocumentType())));
				}
				if (customerInfo.getPeDomicilePlace() != null && !customerInfo.getPeDomicilePlace().equals("")) {
					if (customerInfo.getPeDomicilePlace().equals("1")) {
						customerInfo.setHuji("本地");
					} else if (customerInfo.getPeDomicilePlace().equals("2")) {
						customerInfo.setHuji("省外");
					} else if (customerInfo.getPeDomicilePlace().equals("3")) {
						customerInfo.setHuji("省内");
					} else if (customerInfo.getPeDomicilePlace().equals("4")) {
						customerInfo.setHuji("境外");
					}
				}
				if (customerInfo.getPeResidenceProvinceId() != null
						&& !customerInfo.getPeResidenceProvinceId().equals("")) {
					Area area = areaServiceFacade.selectById(customerInfo.getPeResidenceProvinceId());
					customerInfo.setJusheng(area.getAreaName());
				}
				if (customerInfo.getPeResidenceCityId() != null && !customerInfo.getPeResidenceCityId().equals("")) {
					Area area = areaServiceFacade.selectById(customerInfo.getPeResidenceCityId());
					customerInfo.setJucity(area.getAreaName());
				}
				if (customerInfo.getPeResidenceAreaId() != null && !customerInfo.getPeResidenceAreaId().equals("")) {
					Area area = areaServiceFacade.selectById(customerInfo.getPeResidenceAreaId());
					customerInfo.setJuarea(area.getAreaName());
				}
				if (customerInfo.getPeWorkaroundProvinceId() != null
						&& !customerInfo.getPeWorkaroundProvinceId().equals("")) {
					Area area = areaServiceFacade.selectById(customerInfo.getPeWorkaroundProvinceId());
					customerInfo.setGongsheng(area.getAreaName());
				}
				if (customerInfo.getPeWorkaroundCityId() != null && !customerInfo.getPeWorkaroundCityId().equals("")) {
					Area area = areaServiceFacade.selectById(customerInfo.getPeWorkaroundCityId());
					customerInfo.setGongcity(area.getAreaName());
				}
				if (customerInfo.getPeWorkaroundAreaId() != null && !customerInfo.getPeWorkaroundAreaId().equals("")) {
					Area area = areaServiceFacade.selectById(customerInfo.getPeWorkaroundAreaId());
					customerInfo.setGongarea(area.getAreaName());
				}
				if (null != customerInfo.getPeFrameBrandId()) {
					customerInfo.setPinpai(bcvMap.get(customerInfo.getPeFrameBrandId()));
				}
				if (StringUtils.isNotBlank(customerInfo.getPeActivityType())) {
					customerInfo.setHuodongType(getValue(customerInfo.getPeActivityType(), bcvMap));
				}
				customerInfo.setShouru(
						customerInfo.getPeHouseholdIncome() != null && !customerInfo.getPeHouseholdIncome().equals("")
								? PeHouseholdIncomeEnum.getByNo(customerInfo.getPeHouseholdIncome()).getDes()
								: "");
				if (StringUtils.isNotBlank(customerInfo.getPeHobbyId())) {
					customerInfo.setAihao(getValue(customerInfo.getPeHobbyId(), bcvMap));
				}
				if (StringUtils.isNotBlank(customerInfo.getReCurrentlyProperty())) {
					customerInfo.setJuType(bcvMap.get(Long.parseLong(customerInfo.getReCurrentlyProperty())));
				}
				if (StringUtils.isNotBlank(customerInfo.getReCurrentlyStructure())) {
					customerInfo.setJujie(bcvMap.get(Long.parseLong(customerInfo.getReCurrentlyStructure())));
				}
				customerInfo.setJumian(
						customerInfo.getReCurrentlyArea() != null && !customerInfo.getReCurrentlyArea().equals("")
								? ReCurrentlyAreaEnum.getByNo(customerInfo.getReCurrentlyArea()).getDes()
								: "");

				if (StringUtils.isNotBlank(customerInfo.getReCurrentlyHouse())) {
					customerInfo.setJushu(bcvMap.get(customerInfo.getReCurrentlyHouse()));
				}
				/*
				 * customerInfo.setJushu(customerInfo.getReCurrentlyHouse() != null &&
				 * !customerInfo.getReCurrentlyHouse().equals("") ?
				 * ReCurrentlyHouseEnum.getByNo( customerInfo.getReCurrentlyHouse()).getDes() :
				 * "");
				 */

				customerInfo.setGonglian(
						customerInfo.getCoContactTime() != null && !customerInfo.getCoContactTime().equals("")
								? CoContactTimeEnum.getByNo(customerInfo.getCoContactTime()).getDes()
								: "");
				/*
				 * customerInfo.setGongType(customerInfo.getCoInformationDays() != null &&
				 * !customerInfo.getCoInformationDays().equals("") ?
				 * CoInformationDaysEnum.getByNo( customerInfo.getCoInformationDays()).getDes()
				 * : "");
				 */

				if (StringUtils.isNotBlank(customerInfo.getCoInformationDays())) {
					customerInfo.setGongType(bcvMap.get(customerInfo.getCoInformationDays()));
				}
				if (StringUtils.isNotBlank(customerInfo.getCoWeekendInformation())) {
					customerInfo.setFreeType(bcvMap.get(customerInfo.getCoWeekendInformation()));
				}
				customerInfo.setFreelian(
						customerInfo.getCoContactWeekend() != null && !customerInfo.getCoContactWeekend().equals("")
								? CoContactWeekendEnum.getByNo(customerInfo.getCoContactWeekend()).getDes()
								: "");
				/*
				 * customerInfo.setFreeType(customerInfo.getCoWeekendInformation() != null &&
				 * !customerInfo.getCoWeekendInformation().equals("") ?
				 * CoWeekendInformationEnum.getByNo(
				 * customerInfo.getCoWeekendInformation()).getDes() : "");
				 */

				if (StringUtils.isNotBlank(customerInfo.getInformedWay())) {
					customerInfo.setInformedWayName(bcvMap.get(Long.parseLong(customerInfo.getInformedWay())));
				}
				customerInfo.setRecommendedCategoryName(customerInfo.getRecommendedCategory() != null
						&& !customerInfo.getRecommendedCategory().equals("")
								? RecommendedCategoryEnum.getByNo(customerInfo.getRecommendedCategory()).getDes()
								: "");
				if (customerInfo.getCustomerTradeStatus() != null
						&& !customerInfo.getCustomerTradeStatus().equals("")) {
					if (customerInfo.getCustomerTradeStatus().equals("4")) {
						customerInfo.setIsDuoTao("是");
					} else {
						customerInfo.setIsDuoTao("否");
					}
				} else {
					customerInfo.setIsDuoTao("否");
				}
				if (customerInfo.getUserCode() != null && !customerInfo.getUserCode().equals("")) {
					UserDto dto = new UserDto();
					dto.setUserCode(customerInfo.getUserCode());
					User user = userServiceFacade.selectByDto(dto);
					customerInfo.setUserName(user.getUserName());
				}
				if (customerInfo.getCreateUserId() != null && !customerInfo.getCreateUserId().equals("")) {
					User user = userServiceFacade.selectById(customerInfo.getCreateUserId());
					customerInfo.setCreateName(user.getUserName());
				}

				//添加渠道转客判断.
				//存在手机号,不可编辑
				//获知途径不为空,不可编辑
				//首次接触方式不为空,不可编辑
				customerInfo.setCanEditMobile(true);
				if(StringUtils.isNotEmpty(customerInfo.getCustomerPhone())){
					customerInfo.setCanEditMobile(false);
				}
				customerInfo.setCanEditInformedWay(true);
				if(StringUtils.isNotEmpty(customerInfo.getInformedWay()) && StringUtils.isNotEmpty(customerInfo.getRecommendedChannelId())){
					customerInfo.setCanEditInformedWay(false);
				}
				customerInfo.setCanEditFtContactWay(true);
				if(StringUtils.isNotEmpty(customerInfo.getFtContactWay()) && StringUtils.isNotEmpty(customerInfo.getRecommendedChannelId())){
					customerInfo.setCanEditFtContactWay(false);
				}

				response.success(customerInfo);
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	public String getValue(String str, Map<Long, String> bcvMap) {
		if (StringUtils.isBlank(str))
			return "";
		String[] ids = str.split(",");
		String name = "";
		for (int ii = 0; ii < ids.length; ii++) {
			String id = ids[ii];
			if (bcvMap.get(Long.valueOf(id)) == null) {
				name = "";
			}
			if (StringUtils.isEmpty(bcvMap.get(Long.valueOf(id))) || "null".equals(bcvMap.get(Long.valueOf(id)))) {
				continue;
			}
			name += bcvMap.get(Long.valueOf(id));
			if (ii != (ids.length - 1)) {
				name += ",";
			}
		}
		return name;
	}

	@Override
	public Response<CustomerInfo> findInfoById(Long id) {
		Response<CustomerInfo> response = new Response<CustomerInfo>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			// RoomStatusEnum.getByNo(room.getRoomStatus()).getDes() Info
			Customer entity = service.selectById(id);
			CustomerInfo customerInfo = new CustomerInfo();
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				BaseCodeValueDto bcvDto = new BaseCodeValueDto();
				bcvDto.setMerchantId(entity.getMerchantId());
				bcvDto.setProjectId(entity.getProjectId());
				List<BaseCodeValue> bcvList = baseCodeValueService.selectListFilterDelFlag(bcvDto);
				Map<Long, String> bcvMap = new HashMap<Long, String>();
				if (null != bcvList && bcvList.size() > 0) {
					for (BaseCodeValue bcv : bcvList) {
						bcvMap.put(bcv.getId(), bcv.getCodeName());
					}
				}
				customerInfo = BeanUtil.convert2T(customerInfo, entity);
				Project project = projectService.selectById(customerInfo.getProjectId());
				customerInfo.setProjectName(project.getProjectName());
				customerInfo
						.setSexName(customerInfo.getCustomerSex() != null && !customerInfo.getCustomerSex().equals("")
								? CustomerSexEnum.getByNo(customerInfo.getCustomerSex()).getDes()
								: "");
				customerInfo.setLevelName(
						customerInfo.getIntentionLevel() != null && !customerInfo.getIntentionLevel().equals("")
								? IntentionLevelEnum.getByNo(customerInfo.getIntentionLevel()).getDes()
								: "");
				customerInfo.setStatusName(
						customerInfo.getCustomerStatus() != null && !customerInfo.getCustomerStatus().equals("")
								? CustomerStatusEnum.getByNo(customerInfo.getCustomerStatus()).getDes()
								: "");
				if (StringUtils.isNotBlank(customerInfo.getCustomerOrigin())) {
					customerInfo.setResourceName(bcvMap.get(Long.parseLong(customerInfo.getCustomerOrigin())));
				}
				if (StringUtils.isNotBlank(customerInfo.getRqTheirMotives())) {
					customerInfo.setDongjiName(bcvMap.get(Long.parseLong(customerInfo.getRqTheirMotives())));
				}
				if (StringUtils.isNotBlank(customerInfo.getRqFocusId())) {
					customerInfo.setZhongdianName(getValue(customerInfo.getRqFocusId(), bcvMap));
				}
				customerInfo.setMianji(StringUtils.isNotBlank(customerInfo.getRqDemandArea())
						? RqDemandAreaEnum.getByNo(customerInfo.getRqDemandArea()).getDes()
						: "");
				if (StringUtils.isNotBlank(customerInfo.getRqDemandFloor())) {
					customerInfo.setLouceng(bcvMap.get(Long.parseLong(customerInfo.getRqDemandFloor())));
				}
				if (StringUtils.isNotBlank(customerInfo.getRqLifeSupport())) {
					customerInfo.setPeitao(getValue(customerInfo.getRqLifeSupport(), bcvMap));
				}
				if (StringUtils.isNotBlank(customerInfo.getRqServicesId())) {
					customerInfo.setShenghuo(getValue(customerInfo.getRqServicesId(), bcvMap));
				}
				customerInfo.setZongjia(
						customerInfo.getRqBudgetSumprice() != null && !customerInfo.getRqBudgetSumprice().equals("")
								? RqBudgetSumPriceEnum.getByNo(customerInfo.getRqBudgetSumprice()).getDes()
								: "");
				customerInfo.setDanjia(
						customerInfo.getRqBudgetPrice() != null && !customerInfo.getRqBudgetPrice().equals("")
								? RqBudgetPriceEnum.getByNo(customerInfo.getRqBudgetPrice()).getDes()
								: "");
				if (StringUtils.isNotBlank(customerInfo.getRqCourtyardFunction())) {
					customerInfo.setGongneng(bcvMap.get(Long.parseLong(customerInfo.getRqCourtyardFunction())));
				}
				//绿城来电来访分别有记录,普通版本需特殊对待
				if(MerchantEnum.GREEN_TOWN.getNo().equals(String.valueOf(customerInfo.getMerchantId()))){
					if (StringUtils.isNotBlank(customerInfo.getFtContactWay1())) {
						customerInfo.setJiechuType(bcvMap.get(Long.parseLong(customerInfo.getFtContactWay1())));
					}
				}else{
					if (StringUtils.isNotBlank(customerInfo.getFtContactWay())) {
						customerInfo.setJiechuType(bcvMap.get(Long.parseLong(customerInfo.getFtContactWay())));
					}
				}

				if (StringUtils.isNotBlank(customerInfo.getPeDocumentType())) {
					customerInfo.setZhengjianType(bcvMap.get(Long.parseLong(customerInfo.getPeDocumentType())));
				}
				if (customerInfo.getPeDomicilePlace() != null && !customerInfo.getPeDomicilePlace().equals("")) {
					if (customerInfo.getPeDomicilePlace().equals("1")) {
						customerInfo.setHuji("本地");
					} else if (customerInfo.getPeDomicilePlace().equals("2")) {
						customerInfo.setHuji("省外");
					} else if (customerInfo.getPeDomicilePlace().equals("3")) {
						customerInfo.setHuji("省内");
					} else if (customerInfo.getPeDomicilePlace().equals("4")) {
						customerInfo.setHuji("境外");
					}
				}
				if (customerInfo.getPeResidenceProvinceId() != null
						&& !customerInfo.getPeResidenceProvinceId().equals("")) {
					Area area = areaServiceFacade.selectById(customerInfo.getPeResidenceProvinceId());
					customerInfo.setJusheng(area.getAreaName());
				}
				if (customerInfo.getPeResidenceCityId() != null && !customerInfo.getPeResidenceCityId().equals("")) {
					Area area = areaServiceFacade.selectById(customerInfo.getPeResidenceCityId());
					customerInfo.setJucity(area.getAreaName());
				}
				if (customerInfo.getPeResidenceAreaId() != null && !customerInfo.getPeResidenceAreaId().equals("")) {
					Area area = areaServiceFacade.selectById(customerInfo.getPeResidenceAreaId());
					customerInfo.setJuarea(area.getAreaName());
				}
				if (customerInfo.getPeWorkaroundProvinceId() != null
						&& !customerInfo.getPeWorkaroundProvinceId().equals("")) {
					Area area = areaServiceFacade.selectById(customerInfo.getPeWorkaroundProvinceId());
					customerInfo.setGongsheng(area.getAreaName());
				}
				if (customerInfo.getPeWorkaroundCityId() != null && !customerInfo.getPeWorkaroundCityId().equals("")) {
					Area area = areaServiceFacade.selectById(customerInfo.getPeWorkaroundCityId());
					customerInfo.setGongcity(area.getAreaName());
				}
				if (customerInfo.getPeWorkaroundAreaId() != null && !customerInfo.getPeWorkaroundAreaId().equals("")) {
					Area area = areaServiceFacade.selectById(customerInfo.getPeWorkaroundAreaId());
					customerInfo.setGongarea(area.getAreaName());
				}
				if (null != customerInfo.getPeFrameBrandId()) {
					customerInfo.setPinpai(bcvMap.get(customerInfo.getPeFrameBrandId()));
				}
				if (StringUtils.isNotBlank(customerInfo.getPeActivityType())) {
					customerInfo.setHuodongType(getValue(customerInfo.getPeActivityType(), bcvMap));
				}
				customerInfo.setShouru(
						customerInfo.getPeHouseholdIncome() != null && !customerInfo.getPeHouseholdIncome().equals("")
								? PeHouseholdIncomeEnum.getByNo(customerInfo.getPeHouseholdIncome()).getDes()
								: "");
				if (StringUtils.isNotBlank(customerInfo.getPeHobbyId())) {
					customerInfo.setAihao(getValue(customerInfo.getPeHobbyId(), bcvMap));
				}
				if (StringUtils.isNotBlank(customerInfo.getReCurrentlyProperty())) {
					customerInfo.setJuType(bcvMap.get(Long.parseLong(customerInfo.getReCurrentlyProperty())));
				}
				if (StringUtils.isNotBlank(customerInfo.getReCurrentlyStructure())) {
					customerInfo.setJujie(bcvMap.get(Long.parseLong(customerInfo.getReCurrentlyStructure())));
				}
				customerInfo.setJumian(
						customerInfo.getReCurrentlyArea() != null && !customerInfo.getReCurrentlyArea().equals("")
								? ReCurrentlyAreaEnum.getByNo(customerInfo.getReCurrentlyArea()).getDes()
								: "");

				if (StringUtils.isNotBlank(customerInfo.getReCurrentlyHouse())) {
					customerInfo.setJushu(bcvMap.get(Long.parseLong(customerInfo.getReCurrentlyHouse())));
				}
				/*
				 * customerInfo.setJushu(customerInfo.getReCurrentlyHouse() != null &&
				 * !customerInfo.getReCurrentlyHouse().equals("") ?
				 * ReCurrentlyHouseEnum.getByNo( customerInfo.getReCurrentlyHouse()).getDes() :
				 * "");
				 */
				customerInfo.setGonglian(
						customerInfo.getCoContactTime() != null && !customerInfo.getCoContactTime().equals("")
								? CoContactTimeEnum.getByNo(customerInfo.getCoContactTime()).getDes()
								: "");
				if (StringUtils.isNotBlank(customerInfo.getCoInformationDays())) {
					customerInfo.setGongType(bcvMap.get(Long.parseLong(customerInfo.getCoInformationDays())));
				}
				/*
				 * customerInfo.setGongType(customerInfo.getCoInformationDays() != null &&
				 * !customerInfo.getCoInformationDays().equals("") ?
				 * CoInformationDaysEnum.getByNo( customerInfo.getCoInformationDays()).getDes()
				 * : "");
				 */
				customerInfo.setFreelian(
						customerInfo.getCoContactWeekend() != null && !customerInfo.getCoContactWeekend().equals("")
								? CoContactWeekendEnum.getByNo(customerInfo.getCoContactWeekend()).getDes()
								: "");
				if (StringUtils.isNotBlank(customerInfo.getCoWeekendInformation())) {
					customerInfo.setFreeType(bcvMap.get(Long.parseLong(customerInfo.getCoWeekendInformation())));
				}
				/*
				 * customerInfo.setFreeType(customerInfo.getCoWeekendInformation() != null &&
				 * !customerInfo.getCoWeekendInformation().equals("") ?
				 * CoWeekendInformationEnum.getByNo(
				 * customerInfo.getCoWeekendInformation()).getDes() : "");
				 */
				if (StringUtils.isNotBlank(customerInfo.getInformedWay())) {
					customerInfo.setInformedWayName(bcvMap.get(Long.parseLong(customerInfo.getInformedWay())));
				}
				customerInfo.setRecommendedCategoryName(customerInfo.getRecommendedCategory() != null
						&& !customerInfo.getRecommendedCategory().equals("")
								? RecommendedCategoryEnum.getByNo(customerInfo.getRecommendedCategory()).getDes()
								: "");
				if (customerInfo.getCustomerTradeStatus() != null
						&& !customerInfo.getCustomerTradeStatus().equals("")) {
					if (customerInfo.getCustomerTradeStatus().equals("4")) {
						customerInfo.setIsDuoTao("是");
					} else {
						customerInfo.setIsDuoTao("否");
					}
				} else {
					customerInfo.setIsDuoTao("否");
				}
				if (customerInfo.getUserCode() != null && !customerInfo.getUserCode().equals("")) {
					UserDto dto = new UserDto();
					dto.setUserCode(customerInfo.getUserCode());
					User user = userServiceFacade.selectByDto(dto);
					if (null != user) {
						customerInfo.setUserName(user.getUserName());
					}
				}
				if (customerInfo.getCreateUserId() != null && !customerInfo.getCreateUserId().equals("")) {
					User user = userServiceFacade.selectById(customerInfo.getCreateUserId());
					if (null != user) {
						customerInfo.setCreateName(user.getUserName());
					}
				}
				if (StringUtils.isNotBlank(customerInfo.getRqPaymentMethod())) {
					customerInfo
							.setRqPaymentMethod(PaymentMethodEnum.getByNo(customerInfo.getRqPaymentMethod()).getDes());
				}
				if (StringUtils.isNotBlank(customerInfo.getYixiangwuyeType())) {
					customerInfo
							.setYixiangwuyeType(YiXiangWuYeEnum.getByNo(customerInfo.getYixiangwuyeType()).getDes());
				}
				if (StringUtils.isNotBlank(customerInfo.getBuyCar())) {
					customerInfo.setBuyCar(BuyCarEnum.getByNo(customerInfo.getBuyCar()).getDes());
				}
				if (StringUtils.isNotBlank(customerInfo.getFamilyJie())) {
					customerInfo.setFamilyJie(bcvMap.get(Long.parseLong(customerInfo.getFamilyJie())));
				}
				if (StringUtils.isNotBlank(customerInfo.getXuqiuhuxingType())) {
					customerInfo
							.setXuqiuhuxingType(XuQiuHuXingEnum.getByNo(customerInfo.getXuqiuhuxingType()).getDes());
				}

				if (StringUtils.isNotBlank(customerInfo.getPeAcademicQualifications())) {
					customerInfo.setPeAcademicQualifications(
							bcvMap.get(Long.parseLong(customerInfo.getPeAcademicQualifications())));
				}
				if (StringUtils.isNotBlank(customerInfo.getCongshihangye())) {
					customerInfo.setCongshihangye(bcvMap.get(Long.parseLong(customerInfo.getCongshihangye())));
				}
				if (StringUtils.isNotBlank(customerInfo.getCompanyXingzhi())) {
					customerInfo.setCompanyXingzhi(bcvMap.get(Long.parseLong(customerInfo.getCompanyXingzhi())));
				}
				if (StringUtils.isNotBlank(customerInfo.getRichangxinxi())) {
					customerInfo.setRichangxinxi(getValue(customerInfo.getRichangxinxi(), bcvMap));
				}
				if (StringUtils.isNotBlank(customerInfo.getIsYezhu())) {
					customerInfo.setIsYezhu(IsOwnerCompanyEnum.getByNo(customerInfo.getIsYezhu()).getDes());
				}
				response.success(customerInfo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<Customer> findByDto(CustomerDto dto) {
		ResponseList<Customer> response = new ResponseList<Customer>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<Customer> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<Project> findProjectByDto(CustomerComponentDto entity) {
		ResponseList<Project> response = new ResponseList<Project>();
		try {
			if (null == entity) {
				response.setSuccess(false);
				return response;
			}

			// 数据权限
			if (SysConstants.openDataPermission) {
				String dataPermission = dataPermissionService.dataPermissionCondition(entity.getPermissionUserId(),
						entity.getResourcesCode(), entity.getPrefix(), entity.getColumnName());
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					response.setSuccess(false);
					return response;
				}
				entity.setDataPermission(dataPermissionArr[1]);
			}

			List<Project> list = service.selectCustomerProject(entity);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<BusinessRelation> findBusinessByDto(BusinessRelationDto dto) {
		ResponseList<BusinessRelation> response = new ResponseList<BusinessRelation>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<BusinessRelation> list = businessRelationService.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<Customer> findPageByDto(CustomerDto dto, Integer begin, Integer row) {
		Page<Customer> response = new Page<Customer>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<Customer> page = service.getPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<CustomerComponentDto> findCustomerComponentPage(CustomerComponentDto entity, Integer begin,
			Integer end) {
		Page<CustomerComponentDto> response = new Page<CustomerComponentDto>();
		try {
			if (null == entity || null == begin || null == end) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			// 数据权限
			if (SysConstants.openDataPermission && StringUtils.isNotBlank(entity.getResourcesCode())) {
				String dataPermission = dataPermissionService.dataPermissionCondition(entity.getPermissionUserId(),
						entity.getResourcesCode(), entity.getPrefix(), entity.getColumnName());
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					response.setErrorMsg(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					response.setSuccess(false);
					return response;
				}
				entity.setDataPermission(dataPermissionArr[1]);
			}
			Page<CustomerComponentDto> page = service.selectCustomerComponentPage(entity, begin, end);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}

			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setMerchantId(entity.getMerchantId());
			List<BaseCodeValue> bcvList = baseCodeValueService.selectListFilterDelFlag(bcvDto);
			Map<Long, String> bcvMap = new HashMap<Long, String>();
			if (null != bcvList && bcvList.size() > 0) {
				for (BaseCodeValue bcv : bcvList) {
					bcvMap.put(bcv.getId(), bcv.getCodeName());
				}
			}

			for (CustomerComponentDto ccd : page.getRows()) {
				ccd.setCustomerSexName(StringUtils.isNotBlank(ccd.getCustomerSex())
						? CustomerSexEnum.getByNo(ccd.getCustomerSex()).getDes()
						: "");
				if (StringUtils.isNotBlank(ccd.getCustomerOrigin())) {
					ccd.setCustomerOriginName(bcvMap.get(Long.parseLong(ccd.getCustomerOrigin())));
				}
				if (StringUtils.isNotBlank(ccd.getPeDocumentType())) {
					ccd.setPeDocumentTypeName(bcvMap.get(Long.parseLong(ccd.getPeDocumentType())));
				}

			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	public CustomerComponentDto setValue(CustomerComponentDto entity, Integer begin, Integer end) {

		if (null == entity || null == begin || null == end) {
			entity.setErrorMsg("参数不合法！");
			return entity;
		}

		//2018-09-05_jzliu_去掉查询权限，用户可以查询当前项目下所以客户
		// 数据权限
		/*if (SysConstants.openDataPermission) {
			String dataPermission = dataPermissionService.dataPermissionCondition(entity.getPermissionUserId(),
					entity.getResourcesCode(), entity.getPrefix(), entity.getColumnName());
			String[] dataPermissionArr = dataPermission.split(":");
			if ("00".equals(dataPermissionArr[0])) {
				entity.setErrorMsg(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
				return entity;
			}
			entity.setDataPermission(dataPermissionArr[1]);
		}*/

		if (StringUtils.isNotBlank(entity.getRqDemandArea())) {
			String sql = new String(" and t.rq_demand_area in (");
			String[] audits = entity.getRqDemandArea().split(",");
			String sbsql = "";
			for (int i = 0; i < audits.length; i++) {
				if (audits[i].equals("3")) {
					sbsql = "1,2,3";
				} else {
					sbsql += audits[i];
				}
				if (i != audits.length - 1) {
					sbsql += ",";
				}
			}
			sql += sbsql + ")";
			entity.setRqDemandArea(sql);
		}
		if (entity.getCustomerStatus() != null) {
			switch (entity.getCustomerStatus()) {
			case "1":
				entity.setCustomerStatus(CustomerStatusEnum.TELEPHONE.getNo());
				break;
			case "2":
				entity.setCustomerStatus(CustomerStatusEnum.VISIT.getNo());
				break;
			case "3":
				entity.setCustomerStatus(CustomerStatusEnum.RENCHOU.getNo());
				break;
			// case "4":
			// entity.setCustomerStatus(CustomerStatusEnum.XIAODING.getNo());
			// break;
			case "4":
				entity.setCustomerStatus(CustomerStatusEnum.RENGOU.getNo());
				break;
			case "5":
				entity.setCustomerStatus(CustomerStatusEnum.QIANYUE.getNo());
				break;
			case "6":
				entity.setCustomerStatus(CustomerStatusEnum.DUOTAO.getNo());
				break;
			default:
				break;
			}
		}
		if (StringUtils.isNotBlank(entity.getTabType())) {
			/*
			 * (ym) 1.拼接条件语句 2.通过appendSql参数传入 如 and (id=1 or id=2) and (id<>1 and id<>2) 等
			 */
			String appendSql = service.createTabTypeSql(entity.getTabType(), entity.getMerchantId());
			entity.setAppendSql(appendSql);
		}
		//当使用首次接触方式当查询条件时，判断是来电还是来访
		entity.setFtContactWayType("1");
		if(StringUtils.isNotBlank(entity.getFtContactWay())) {
			if(MerchantEnum.GREEN_TOWN.getNo().equals(String.valueOf(entity.getMerchantId()))){
				String ftContactWayType = getFtContactWayType(entity.getFtContactWay());
				entity.setFtContactWayType(ftContactWayType);
			}
		}
		return entity;
	}
	
	/**
	 * 判断是来电还是来访
	 * @param id
	 * @return type 1 来电 2来访
	 */
	private String getFtContactWayType(String id) {
		String type = "";
		BaseCodeValue bcv = baseCodeValueService.selectById(Long.parseLong(id));
		if(bcv != null) {
			if("来电".equals(bcv.getCodeName())) {
				type = "1";
			} else if("来访".equals(bcv.getCodeName()) 
					|| "电转访".equals(bcv.getCodeName())){
				type = "2";
			}
		}

		return type;
	}
	
	/**
	 * 获取权限
	 * @param entity
	 * @return
	 */
	private String getDataPermission(CustomerComponentDto entity) {
		String dataPermission = dataPermissionService.dataPermissionCondition(entity.getPermissionUserId(),
				entity.getResourcesCode(), entity.getPrefix(), entity.getColumnName());
		String[] dataPermissionArr = dataPermission.split(":");
		return dataPermissionArr[1];
	}

	@Override
	public Page<CustomerComponentDto> findCustomerPage(CustomerComponentDto entity, Integer begin, Integer end) {
		Page<CustomerComponentDto> response = new Page<CustomerComponentDto>();
		response.setPageSize(end);
		try {
			entity = setValue(entity, begin, end);
			if (entity.getErrorMsg() != null && entity.getErrorMsg() != "") {
				response.setSuccess(false);
				response.setErrorMsg(entity.getErrorMsg());
				return response;
			}
			//获取权限
			String dataPermission = getDataPermission(entity);
			entity.setDataPermission(dataPermission);

			Page<CustomerComponentDto> page = service.selectCustomerPage(entity, begin, end);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setMerchantId(entity.getMerchantId());
			List<BaseCodeValue> bcvList = baseCodeValueService.selectListFilterDelFlag(bcvDto);
			Map<Long, String> bcvMap = new HashMap<Long, String>();
			if (null != bcvList && bcvList.size() > 0) {
				for (BaseCodeValue bcv : bcvList) {
					bcvMap.put(bcv.getId(), bcv.getCodeName());
				}
			}
			for (CustomerComponentDto ccd : page.getRows()) {
				ccd.setCustomerSexName(StringUtils.isNotBlank(ccd.getCustomerSex())
						? CustomerSexEnum.getByNo(ccd.getCustomerSex()).getDes()
						: "");
				if (StringUtils.isNotBlank(ccd.getInformedWay())) {
					ccd.setCustomerOriginName(bcvMap.get(Long.parseLong(ccd.getInformedWay())));
				}
				if (StringUtils.isNotBlank(ccd.getPeDocumentType())) {
					ccd.setPeDocumentTypeName(bcvMap.get(Long.parseLong(ccd.getPeDocumentType())));
				}
				if (StringUtils.isNotBlank(ccd.getIntentionLevel())) {
					ccd.setIntentionLevelName(IntentionLevelEnum.getByNo(ccd.getIntentionLevel()).getDes());
				}
				if (StringUtils.isNotBlank(ccd.getFtContactWay())) {
					ccd.setFtContactWayType(bcvMap.get(Long.parseLong(ccd.getFtContactWay())));
				}
				// 计算日期差
				if (ccd.getFillInfoTime() != null) {
					ccd.setFillInfoDay(dateDifference(ccd.getFillInfoTime()));
				}
				//当有首次来电，且无来访和电转访时，给予新增电转访权限
				ccd.setIsCallToVisit("0");
				if(MerchantEnum.GREEN_TOWN.getNo().equals(String.valueOf(ccd.getMerchantId()))
					|| MerchantEnum.GREEN_TOWN_TEST.getNo().equals(String.valueOf(ccd.getMerchantId()))){
					if(StringUtils.isNotBlank(ccd.getFtContactWay())
							&& StringUtils.isBlank(ccd.getFtContactWay1())) {
						ccd.setIsCallToVisit("1");
					}
				}else{
					//非绿城商户,无问卷系统,不需要客户标签
					ccd.setCusTag("0");
				}

				//判断是否拥有查看权限
				ccd.setDataAuthority(
					getCustomerListManage.dataAuthority(ccd.getAccessCode(), 
							ccd.getUserCode(), 
							ccd.getSalesGroupId() == null ?null:ccd.getSalesGroupId().toString(),
							dataPermission)
				);
				//没有查看权限时
				if(!"1".equals(ccd.getDataAuthority())) {
					//隐藏手机号中间四位
					ccd.setCustomerPhone(phone(ccd.getCustomerPhone()));
					//清除字段内容
					setFieldIsNull(ccd);
				}else {
					//有权限时，给被分配且未跟进客户增加颜色标识
					setFieldIsColor(ccd);
				}
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	// 计算最后编辑时间与当前时间相隔几天
	private long dateDifference(Date fillInfoTime) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(fillInfoTime);
		long time1 = cal.getTimeInMillis();
		cal.setTime(new Date());
		long time2 = cal.getTimeInMillis();
		long day = (time2 - time1) / (1000 * 3600 * 24);
		return day;
	}
	
	/**
	 * 隐藏手机号中间4位
	 * @param customerPhone
	 * @return
	 */
	private String phone(String customerPhone) {
		customerPhone = customerPhone.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
		return customerPhone;
	}

	/**
	 * 没有权限时,设置字段为null
	 * @param ccd
	 */
	private void setFieldIsNull(CustomerComponentDto ccd) {
		ccd.setCustomerStatus(null);
		ccd.setFtContactContent(null);
		ccd.setFtContactContent1(null);
		ccd.setLastFollowTime(null);
		ccd.setFollowContent(null);
		ccd.setFollowMonth(null);
		ccd.setIntentionLevel(null);
		ccd.setCustomerTradeStatus(null);
		ccd.setCustomerOriginName(null);
	}
	/**
	 * 有权限时，给被分配且未跟进客户增加颜色标识
	 * @param ccd
	 */
	private void setFieldIsColor(CustomerComponentDto ccd) {
		if("0".equals(ccd.getProcessStatus())) {
			ccd.setCustomerPhone(setColor(ccd.getCustomerPhone()));
			ccd.setFtContactContent(setColorAndTitle(ccd.getFtContactContent()));
			ccd.setFtContactContent1(setColorAndTitle(ccd.getFtContactContent1()));
			ccd.setFollowMonth(setColor(ccd.getFollowMonth()));
			ccd.setCustomerOriginName(setColor(ccd.getCustomerOriginName()));
			ccd.setUserName(setColor(ccd.getUserName()));
		}
	}
	private String setColor(String value) {
		if(StringUtils.isBlank(value)) {
			return null;
		}
		StringBuffer sb = new StringBuffer();
		sb.append("<font style=\"color:#990033\">");
		sb.append(value);
		sb.append("</font>");
		return sb.toString();
	}
	private String setColorAndTitle(String value) {
		if(StringUtils.isBlank(value)) {
			return null;
		}
		StringBuffer sb = new StringBuffer();
		sb.append("<font style=\"color:#990033\" title=\""+value+"\">");
		sb.append(value);
		sb.append("</font>");
		return sb.toString();
	}
	@Override
	public ResponseList<CustomerComponentDto> selectCustomerAll(CustomerComponentDto entity) {
		ResponseList<CustomerComponentDto> response = new ResponseList<CustomerComponentDto>();
		try {
			// 组装参数，由于与分页查询通用一个方法，因此0和5是为不报错而设置的入参，无意义，不参与查询
			entity = setValue(entity, 0, 5);
			if (entity.getErrorMsg() != null && entity.getErrorMsg() != "") {
				response.setSuccess(false);
				response.fail("9999", entity.getErrorMsg());
				return response;
			}
			List<CustomerComponentDto> list = service.selectCustomerAll(entity);
			if (null == list) {
				response.setSuccess(false);
				response.fail("9999", "分页数据不存在");
				return response;
			}
			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setMerchantId(entity.getMerchantId());
			List<BaseCodeValue> bcvList = baseCodeValueService.selectListFilterDelFlag(bcvDto);
			Map<Long, String> bcvMap = new HashMap<Long, String>();
			if (null != bcvList && bcvList.size() > 0) {
				for (BaseCodeValue bcv : bcvList) {
					bcvMap.put(bcv.getId(), bcv.getCodeName());
				}
			}
			for (CustomerComponentDto ccd : list) {
				ccd.setCustomerSexName(StringUtils.isNotBlank(ccd.getCustomerSex())
						? CustomerSexEnum.getByNo(ccd.getCustomerSex()).getDes()
						: "");
				if (StringUtils.isNotBlank(ccd.getInformedWay())) {
					ccd.setCustomerOriginName(bcvMap.get(Long.parseLong(ccd.getInformedWay())));
				}
				if (StringUtils.isNotBlank(ccd.getFtContactWay())) {
					ccd.setFtContactWay(bcvMap.get(Long.parseLong(ccd.getFtContactWay())));
				}
				if (StringUtils.isNotBlank(ccd.getPeDocumentType())) {
					ccd.setPeDocumentTypeName(bcvMap.get(Long.parseLong(ccd.getPeDocumentType())));
				}
				if (StringUtils.isNotBlank(ccd.getIntentionLevel())) {
					ccd.setIntentionLevelName(IntentionLevelEnum.getByNo(ccd.getIntentionLevel()).getDes());
				}
			}
			response.setEntity(list);
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.fail("99999", "系统异常");
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public DistributionConsultantResDto distributionConsultant(DistributionConsultantReqDto reqDto) {
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、分配职业顾问
		return distributionConsultantManage.distributionConsultant(reqDto);
	}

	@Override
	public AddFollowResDto addFollow(AddFollowReqDto reqDto) {
		// 1、版本校验(待定)
		// 2、客户验签(待定)
		// 3、获取当前登录用户
		// 4、新增跟进
		return addFollowManage.addFollow(reqDto);
	}

	@Override
	public Page<Image> findImagePageByDto(ImageDto dto, Integer begin, Integer row) {
		Page<Image> response = new Page<Image>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<Image> page = imageService.getPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<Customer> selectCustomerPhoneByListPC(CustomerDto dto) {
		ResponseList<Customer> response = new ResponseList<Customer>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<Customer> list = service.selectCustomerPhoneByListPC(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<CustomerComponentDto> findCustomerPageByNameOrPhone(CustomerComponentDto entity, Integer begin,
			Integer end, boolean needPermission) {
		Page<CustomerComponentDto> response = new Page<CustomerComponentDto>();
		response.setPageSize(end);
		try {

			if (null == entity || null == begin || null == end) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}

			// 数据权限
			String data_permission = null;
			if (SysConstants.openDataPermission && needPermission) {
				String dataPermission = dataPermissionService.dataPermissionCondition(entity.getPermissionUserId(),
						entity.getResourcesCode(), entity.getPrefix(), entity.getColumnName());
				String[] dataPermissionArr = dataPermission.split(":");
				data_permission = dataPermissionArr[1];
//				if ("00".equals(dataPermissionArr[0])) {
//					response.setErrorMsg(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
//					response.setSuccess(false);
//					return response;
//				}
//				entity.setDataPermission(dataPermissionArr[1]);
			}

			String appendSql = "";
			if (StringUtils.isNotBlank(entity.getTabType())) {
				/*
				 * (ym) 1.拼接条件语句 2.通过appendSql参数传入 如 and (id=1 or id=2) and (id<>1 and id<>2) 等
				 */
				appendSql = service.createTabTypeSql(entity.getTabType(), entity.getMerchantId());
				entity.setAppendSql(appendSql);
			}

			if (StringUtils.isNotBlank(entity.getCustomerPhone())) {
				if (StringUtils.isNotEmpty(appendSql)) {
					appendSql += " and ";
				}
				appendSql += "(t.customer_phone = " + entity.getCustomerPhone() + " or t.pe_mobile = "
						+ entity.getCustomerPhone() + ")";
				entity.setAppendSql(appendSql);
			}

			Page<CustomerComponentDto> page = service.findCustomerPageByNameOrPhone(entity, begin, end);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setMerchantId(entity.getMerchantId());
			List<BaseCodeValue> bcvList = baseCodeValueService.selectListFilterDelFlag(bcvDto);
			Map<Long, String> bcvMap = new HashMap<Long, String>();
			if (null != bcvList && bcvList.size() > 0) {
				for (BaseCodeValue bcv : bcvList) {
					bcvMap.put(bcv.getId(), bcv.getCodeName());
				}
			}
			for (CustomerComponentDto ccd : page.getRows()) {
				ccd.setCustomerSexName(StringUtils.isNotBlank(ccd.getCustomerSex())
						? CustomerSexEnum.getByNo(ccd.getCustomerSex()).getDes()
						: "");
				if (StringUtils.isNotBlank(ccd.getInformedWay())) {
					ccd.setCustomerOriginName(bcvMap.get(Long.parseLong(ccd.getInformedWay())));
				}
				if (StringUtils.isNotBlank(ccd.getFtContactWay())) {
					ccd.setFtContactWay(bcvMap.get(Long.parseLong(ccd.getFtContactWay())));
				}
				if (StringUtils.isNotBlank(ccd.getPeDocumentType())) {
					ccd.setPeDocumentTypeName(bcvMap.get(Long.parseLong(ccd.getPeDocumentType())));
				}
				// 计算日期差
				if (ccd.getFillInfoTime() != null) {
					ccd.setFillInfoDay(dateDifference(ccd.getFillInfoTime()));
				}
				//当有首次来电，且无来访和电转访时，给予新增电转访权限
				if(StringUtils.isNotBlank(ccd.getFtContactWay())
						&& StringUtils.isBlank(ccd.getFtContactWay1())) {
					ccd.setIsCallToVisit("1");
				}else {
					ccd.setIsCallToVisit("0");
				}
				//判断是否拥有查看权限
				ccd.setDataAuthority(
					getCustomerListManage.dataAuthority(ccd.getAccessCode(), 
							ccd.getUserCode(), 
							ccd.getSalesGroupId() == null ?null:ccd.getSalesGroupId().toString(),
							data_permission)
				);
				//没有查看权限时
				if(!"1".equals(ccd.getDataAuthority())) {
					//隐藏手机号中间四位
					ccd.setCustomerPhone(phone(ccd.getCustomerPhone()));
					//清除字段内容
					setFieldIsNull(ccd);
				}else {
					//有权限时，给被分配且未跟进客户增加颜色标识
					setFieldIsColor(ccd);
				}
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> selectCustomerCount(CustomerComponentDto entity) {
		Response<Integer> response = new Response<>(true);
		entity = setValue(entity, 0, 10);
		Integer count = service.cusCount(entity);
		if (count == null) {
			response.setEntity(0);
		} else {
			response.setEntity(count);
		}
		return response;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.emm.yixun.customer.service.CustomerServiceFacade#selectListByDto(com.emm.
	 * yixun.common.model.dto.ImageDto)
	 */
	@Override
	public ResponseList<Image> selectListByDto(ImageDto dto) {
		ResponseList<Image> response = new ResponseList<Image>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<Image> list = imageService.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<Customer> selectCustomerListByDto(CustomerDto dto) {
		ResponseList<Customer> response = new ResponseList<Customer>();
		List<Customer> customerList = service.selectListByDto(dto);
		response.success(customerList);
		return response;
	}

	@Override
	public String queryCustomerBusiness(Long id) {
		return service.queryCustomerBusiness(id);
	}

	@Override
	public Response<Boolean> hotfixCustomerSignedInfo(List<SignedCustomerVo> list, Long projectId) {
		Response<Boolean> response = new Response<Boolean>();
		try {
			initBaseCodeMap(projectId);
			int i = 1;
			if (list != null && list.size() > 0) {
				for (SignedCustomerVo signedCustomer : list) {
					CustomerDto customerDto = new CustomerDto();
					customerDto.setProjectId(projectId);
					customerDto.setCustomerName(signedCustomer.getCustomerName());
					customerDto.setCustomerPhone(signedCustomer.getCustomerPhone());
					customerDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					Customer customer = service.selectByDto(customerDto);
					if (customer == null) {
						continue;
					}
					CustomerDto updateCustomer = new CustomerDto();
					BeanUtil.convert2T(updateCustomer, customer);
					BeanUtil.convert2T(updateCustomer, signedCustomer);
					updateCustomer
							.setPeAcademicQualifications(findBaseValueId(updateCustomer.getPeAcademicQualifications())); // 学历
					updateCustomer.setCongshihangye(findBaseValueId(updateCustomer.getCongshihangye())); // 从事行业
					updateCustomer.setCompanyXingzhi(findBaseValueId(updateCustomer.getCompanyXingzhi())); // 公司性质
					String peFrameBrand = findBaseValueId(signedCustomer.getPeFrameBrandId()); // 车架品牌
					if (peFrameBrand != null) {
						updateCustomer.setPeFrameBrandId(new Long(peFrameBrand));
					}
					updateCustomer.setFamilyJie(findBaseValueId(updateCustomer.getFamilyJie()));// 家庭结构
					PeHouseholdIncomeEnum income = PeHouseholdIncomeEnum
							.getByDescription(updateCustomer.getPeHouseholdIncome());// 家庭年收入
					if (income != null) {
						updateCustomer.setPeHouseholdIncome(income.getNo());
					}
					updateCustomer.setPeHobbyId(findBaseValueId(updateCustomer.getPeHobbyId()));// 兴趣爱好

					updateCustomer.setPeActivityType(findBaseValueId(updateCustomer.getPeActivityType()));// 乐于参与的活动类型

					DelFlagEnum isLs = DelFlagEnum.getByDescription(updateCustomer.getIsLaoren()); // 是否老人同住
					if (isLs != null) {
						updateCustomer.setIsLaoren(isLs.getNo());
					}
					DelFlagEnum iszn = DelFlagEnum.getByDescription(updateCustomer.getIsZinv()); // 是否有子女
					if (iszn != null) {
						updateCustomer.setIsZinv(iszn.getNo());
					}
					if (!StringUtils.isEmpty(signedCustomer.getReCurrentHoldings())) { // 住宅数
						updateCustomer.setReCurrentHoldings(new Long(signedCustomer.getReCurrentHoldings()));
					}

					updateCustomer.setReCurrentlyProperty(findBaseValueId(updateCustomer.getReCurrentlyProperty())); // 物业类型
					ReCurrentlyAreaEnum currentLy = ReCurrentlyAreaEnum
							.getByDescription(updateCustomer.getReCurrentlyArea());
					if (currentLy != null) {
						updateCustomer.setReCurrentlyArea(currentLy.getNo()); // 居住面积
					}

					updateCustomer.setRqTheirMotives(findBaseValueId(updateCustomer.getRqTheirMotives())); // 置业动机
					updateCustomer.setRqLifeSupport(findBaseValueId(updateCustomer.getRqLifeSupport())); // 生活配套
					updateCustomer.setRqServicesId(findBaseValueId(updateCustomer.getRqServicesId())); // 生活服务
					BuyCarEnum buy = BuyCarEnum.getByDescription(updateCustomer.getBuyCar());
					if (buy != null) {
						updateCustomer.setBuyCar(buy.getNo());
					}
					service.update(updateCustomer);
					System.err.println("客户姓名:" + signedCustomer.getCustomerName() + ",次数:" + i);
					i++;

				}
				response.setEntity(true);
				response.setSuccess(true);
			}
		} catch (Exception e) {
			response.setEntity(false);
			response.setSuccess(false);
			response.setResultMessage(e.getMessage());
			logger.error("hotfixCustomerSignedInfo error: ", e);
		}
		return response;
	}

	public String findBaseValueId(String baseCodeValue) {
		if (StringUtils.isEmpty(baseCodeValue)) {
			return null;
		}
		if (dicMap != null && dicMap.size() > 0) {
			Long valId = dicMap.get(baseCodeValue);
			if (valId != null) {
				return valId.toString();
			}
		}
		return null;
	}

	public void initBaseCodeMap(Long projectId) {

		Project project = projectService.selectById(projectId);

		BaseCodeValueDto baseCodeEntity = new BaseCodeValueDto();
		baseCodeEntity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		baseCodeEntity.setMerchantId(project.getMerchantId());
		List<BaseCodeValue> baseValueList = baseCodeValueService.selectListByDto(baseCodeEntity);
		if (baseValueList != null && baseValueList.size() > 0) {
			for (BaseCodeValue val : baseValueList) {
				if (dicMap.get(val.getCodeName()) == null) {
					dicMap.put(val.getCodeName(), val.getId());
				}
			}
		}

	}

	////////////////////////////////////////////////// 客户信息与意向登记不对应的用户///////////////////////////////////////////////////////////////
	@Override
	public int findIntentionIntactCount(CustomerComponentDto entity) {
		if (null == entity) {
			return 0;
		}
		// if(StringUtils.isEmpty(entity.getUserCode())){
		// return 0;
		// }
		int count = service.findIntentionIntactCount(entity);
		return count;
	}

	@Override
	public Page<CustomerComponentDto> findCustomerIntentionPage(CustomerComponentDto entity, Integer begin,
			Integer end) {
		Page<CustomerComponentDto> response = new Page<CustomerComponentDto>();
		response.setPageSize(end);
		try {
			entity = setValue(entity, begin, end);
			if (entity.getErrorMsg() != null && entity.getErrorMsg() != "") {
				response.setSuccess(false);
				response.setErrorMsg(entity.getErrorMsg());
				return response;
			}
			Page<CustomerComponentDto> page = service.selectCustomerItentionPage(entity, begin, end);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setMerchantId(entity.getMerchantId());
			List<BaseCodeValue> bcvList = baseCodeValueService.selectListFilterDelFlag(bcvDto);
			Map<Long, String> bcvMap = new HashMap<Long, String>();
			if (null != bcvList && bcvList.size() > 0) {
				for (BaseCodeValue bcv : bcvList) {
					bcvMap.put(bcv.getId(), bcv.getCodeName());
				}
			}
			for (CustomerComponentDto ccd : page.getRows()) {
				ccd.setCustomerSexName(StringUtils.isNotBlank(ccd.getCustomerSex())
						? CustomerSexEnum.getByNo(ccd.getCustomerSex()).getDes()
						: "");
				if (StringUtils.isNotBlank(ccd.getInformedWay())) {
					ccd.setCustomerOriginName(bcvMap.get(Long.parseLong(ccd.getInformedWay())));
				}
				if (StringUtils.isNotBlank(ccd.getFtContactWay())) {
					ccd.setFtContactWay(bcvMap.get(Long.parseLong(ccd.getFtContactWay())));
				}
				if (StringUtils.isNotBlank(ccd.getPeDocumentType())) {
					ccd.setPeDocumentTypeName(bcvMap.get(Long.parseLong(ccd.getPeDocumentType())));
				}
				if (StringUtils.isNotBlank(ccd.getIntentionLevel())) {
					ccd.setIntentionLevelName(IntentionLevelEnum.getByNo(ccd.getIntentionLevel()).getDes());
				}
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<ContactWayDto> queryProjectFtContactWay(String startTime, String endDate, String oaId) {
		ResponseList<ContactWayDto> responseList = new ResponseList<ContactWayDto>();
		try {
			UserDto queryUser = new UserDto();
			queryUser.setOaUserCode(oaId);
			User user = userServiceFacade.selectByDto(queryUser);
			if (user == null) {
				return responseList;
			}
			ContactWayDto query = new ContactWayDto();
			query.setCreateStartTime(startTime);
			query.setCreateEndTime(endDate);
			query.setMerchantId(user.getMerchantId());
			// 数据权限
			if (SysConstants.openDataPermission) {
				String dataPermission = dataPermissionService.dataPermissionCondition(user.getId(), "menu_0003_0001",
						"t11", null);
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					logger.error(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					return responseList;
				}
				query.setDataPermission(dataPermissionArr[1]);
			}
			List<ContactWayDto> list = service.queryProjectFtContactWay(query);
			// 来电
			Long countCallFrequency = 0L;
			Long countVisitFrequency = 0L;
			Long countTotal = 0L;
			if (list != null && list.size() > 0) {
				for (ContactWayDto entity : list) {
					entity.setAll(false);
					if (!StringUtils.isEmpty(entity.getCallFrequency())) {
						countCallFrequency += new Long(entity.getCallFrequency());
					} else {
						entity.setCallFrequency("0");
					}
					// 来访
					if (!StringUtils.isEmpty(entity.getVisitFrequency())) {
						countVisitFrequency += new Long(entity.getVisitFrequency());
					} else {
						entity.setVisitFrequency("0");
					}
					// 合计的合计
					if (!StringUtils.isEmpty(entity.getTotal())) {
						countTotal += new Long(entity.getTotal());
					} else {
						entity.setTotal("0");
					}
				}
				ContactWayDto dto = new ContactWayDto();
				dto.setAll(true);
				dto.setProjectId(1000000000L);
				dto.setTotal(countTotal.toString());
				dto.setCallFrequency(countCallFrequency.toString());
				dto.setVisitFrequency(countVisitFrequency.toString());
				list.add(dto);
			}
			responseList.setEntity(list);
		} catch (Exception e) {
			logger.error("queryProjectFtContactWay error: ", e);
		}
		return responseList;
	}

	@Override
	public ResponseList<HighchartsDto> queryCustomerLevel(List<ContactWayDto> list, String startTime, String endTime) {
		ResponseList<HighchartsDto> responseList = new ResponseList<HighchartsDto>();
		try {
			LinkedList<HighchartsDto> higList = new LinkedList<HighchartsDto>();
			List<Long> allList = new ArrayList<Long>();
			if(null != allList && allList.size() > 0) {
				for (ContactWayDto way : list) {
					ContactWayDto query = new ContactWayDto();
					query.setCreateStartTime(startTime);
					query.setCreateEndTime(endTime);
					if (way.isAll()) {
						continue;
					} else {
						if (way.getProjectId() == null) {
							continue;
						}
						query.setProjectId(way.getProjectId());
						HashMap<String, Long> map = service.queryCustomerLevel(query);
						Project project = projectService.selectById(way.getProjectId());
						if (map != null && map.size() > 0) {
							HighchartsDto dto = new HighchartsDto();
							List<Long> array = getCustomerLevel(map);
							allList.addAll(array);

							dto.setData(array);
							dto.setName(project.getProjectName());
							higList.add(dto);
						} else {
							HighchartsDto dto = new HighchartsDto();
							dto.setName(project.getProjectName());
							List<Long> array = new ArrayList<Long>();
							allList.addAll(array);
							higList.add(dto);
						}

					}
				}
			}
			responseList.setEntity(higList);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("queryCustomerLevel error: ", e);
		}
		return responseList;
	}

	public List<Long> getCustomerLevel(HashMap<String, Long> map) {
		List<Long> array = new ArrayList<Long>();
		for (IntentionLevelEnum intentionLevelEnum : IntentionLevelEnum.values()) {
			Long val = map.get(intentionLevelEnum.getDes());
			if (val != null) {
				array.add(val);
			}
		}
		return array;
	}

	@Override
	public ResponseList<SalesReportAppDto> queryProjectSignedInfo(String startTime, String endTime, String oaId) {
		ResponseList<SalesReportAppDto> responseList = new ResponseList<SalesReportAppDto>();
		UserDto queryUser = new UserDto();
		queryUser.setOaUserCode(oaId);
		User user = userServiceFacade.selectByDto(queryUser);
		try {
			if (user == null) {
				return responseList;
			}
			ContactWayDto query = new ContactWayDto();
			query.setCreateStartTime(startTime);
			query.setCreateEndTime(endTime);
			ProjectDto entity = new ProjectDto();
			// 数据权限
			if (SysConstants.openDataPermission) {
				String dataPermission = dataPermissionService.dataPermissionCondition(user.getId(), "menu_0003_0001",
						"t", null);
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					logger.error(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					return responseList;
				}
				query.setDataPermission(dataPermissionArr[1]);
				entity.setDataPermission(dataPermissionArr[1]);
			}

			entity.setMerchantId(user.getMerchantId());
			List<Project> projectList = projectService.selectListByDto(entity);
			List<SalesReportDto> entityList = service.queryProjectSignedInfo(query);
			List<Long> projectids = getProjectIds(projectList, entityList);
			query.setProjectIds(projectids);
			List<SalesReportDto> projectOther = service.queryProjectSignedInfoByIds(query);
			entityList.addAll(projectOther);
			if (null != entityList && entityList.size() > 0) {
				for (SalesReportDto dto : entityList) {
					if (dto.getSignedArea() != null && dto.getSoldArea() != null) {
						if (dto.getAmountTotal() != null && dto.getAreaTotal() != null
								&& dto.getAreaTotal().compareTo(BigDecimal.ZERO) != 0) {
							dto.setAvgAmount(MathUtil.bigDivide(dto.getAmountTotal(), dto.getAreaTotal(), 2));
						}
					}
				}
				List<SalesReportAppDto> dataList = getList(entityList);
				responseList.setEntity(dataList);
				responseList.setSuccess(true);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return responseList;
	}

	public List<Long> getProjectIds(List<Project> list, List<SalesReportDto> salesData) {
		List<Long> set = new ArrayList<Long>();
		if (list != null && !list.isEmpty() && salesData != null && !salesData.isEmpty()) {
			for (int i = 0; i < list.size(); i++) {
				set.add(list.get(i).getId());
			}
			for (SalesReportDto sales : salesData) {
				if (set.contains(sales.getProjectId())) {
					set.remove(sales.getProjectId());
				}
			}
		}
		return set;
	}

	public List<SalesReportAppDto> getList(List<SalesReportDto> entityList) {
		List<SalesReportAppDto> list = new ArrayList<SalesReportAppDto>();
		Map<String, List<SalesReportDto>> map = mapSalesReport(entityList);
		if (!map.isEmpty()) {
			for (Map.Entry<String, List<SalesReportDto>> entry : map.entrySet()) {
				// 小计
				SalesReportDto count = new SalesReportDto();
				count.setTypeName("小计");
				
				for (SalesReportDto totalObj : entry.getValue()) {
					if (totalObj.getAreaTotal() != null) { // 销售面积
						count.setAreaTotal(totalObj.getAreaTotal()
								.add(count.getAreaTotal() == null ? BigDecimal.ZERO : count.getAreaTotal()));
					}
					if (totalObj.getAmountTotal() != null) {
						count.setAmountTotal(totalObj.getAmountTotal()
								.add(count.getAmountTotal() == null ? BigDecimal.ZERO : count.getAmountTotal()));
					}
					if (totalObj.getAvgAmount() != null) {
						count.setAvgAmount(totalObj.getAvgAmount()
								.add(count.getAvgAmount() == null ? BigDecimal.ZERO : count.getAvgAmount()));
					}
					if (totalObj.getBackAmount() != null) {
						count.setBackAmount(totalObj.getBackAmount()
								.add(count.getBackAmount() == null ? BigDecimal.ZERO : count.getBackAmount()));
					}
				}
				entry.getValue().add(count);
				BigDecimal result = projectRoomService.getRemovalRate(entry.getKey());
				SalesReportAppDto data = new SalesReportAppDto(entry.getKey(),result, entry.getValue());
				
				list.add(data);
			}
		}
		return list;

	}

	public Map<String, List<SalesReportDto>> mapSalesReport(List<SalesReportDto> entityList) {
		Map<String, List<SalesReportDto>> map = new HashMap<>();
		if (entityList != null && !entityList.isEmpty()) {
			for (SalesReportDto dto : entityList) {
				if (!StringUtils.isEmpty(dto.getTypeName())) {
					List<SalesReportDto> projectChild = map.get(dto.getProjectName());
					if (projectChild == null) {
						List<SalesReportDto> dtoList = new ArrayList<>();
						dtoList.add(dto);
						map.put(dto.getProjectName(), dtoList);
					} else {
						projectChild.add(dto);
						map.put(dto.getProjectName(), projectChild);
					}
				}
			}
		}
		return map;
	}

	@Override
	public List<String[]> getSubjectRatio(CustomerDto dto, String num) {
		// ResponseList<String[]> response = new ResponseList<String[]>();
		List<String[]> ratioList = new ArrayList<String[]>();
		try {
			if (null == dto) {
				// response.fail(ResponseCode.PARAM_INVALID.getCode(),
				// ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return ratioList;
			}
			Customer cus = service.getSubjectRatio(dto);
			if (null == cus) {
				// response.fail(ResponseCode.NO_DATA_FOUND.getCode(),
				// ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return ratioList;
			}
			// List<String[]> ratioList = new ArrayList<String[]>();
			// 将num转换为BigDecimal
			BigDecimal cusNum = new BigDecimal(num);
			// 设置百分比
			BigDecimal ro = new BigDecimal("100");
			// 计算答题率
			ratioList.add(getRatio(ro, cusNum, cus.getCustomerSex(), "customerSex")); // 性别
			ratioList.add(getRatio(ro, cusNum, cus.getIntentionLevel(), "intentionLevel")); // 意向等级
			ratioList.add(getRatio(ro, cusNum, cus.getCustomerStatus(), "customerStatus")); // 客户状态
			ratioList.add(getRatio(ro, cusNum, cus.getCustomerOrigin(), "customerOrigin")); // 客户性质
			ratioList.add(getRatio(ro, cusNum, cus.getInformedWay(), "informedWay_t")); // 获知途径
			ratioList.add(getRatio(ro, cusNum, cus.getRqTheirMotives(), "rqTheirMotives")); // 置业动机
			ratioList.add(getRatio(ro, cusNum, cus.getRqFocusId(), "rqFocusId")); // 关注重点
			ratioList.add(getRatio(ro, cusNum, cus.getRqDemandArea(), "rqDemandArea")); // 需求面积
			ratioList.add(getRatio(ro, cusNum, cus.getRqDemandFloor(), "rqDemandFloor")); // 需求楼层
			ratioList.add(getRatio(ro, cusNum, cus.getRqServicesId(), "rqServicesId")); // 生活服务
			ratioList.add(getRatio(ro, cusNum, cus.getRqLifeSupport(), "rqLifeSupport")); // 生活配套
			ratioList.add(getRatio(ro, cusNum, cus.getRqBudgetSumprice(), "rqBudgetSumprice")); // 预算总价
			ratioList.add(getRatio(ro, cusNum, cus.getRqBudgetPrice(), "rqBudgetPrice")); // 预算单价
			ratioList.add(getRatio(ro, cusNum, cus.getRqCourtyardFunction(), "rqCourtyardFunction")); // 希望庭院具备功能
			ratioList.add(getRatio(ro, cusNum, cus.getRqPaymentMethod(), "rqPaymentMethod")); // 付款方式
			ratioList.add(getRatio(ro, cusNum, cus.getFamilyJie(), "familyJie_t")); // 家庭结构
			ratioList.add(getRatio(ro, cusNum, cus.getBuyCar(), "buyCar")); // 购买车位
			ratioList.add(getRatio(ro, cusNum, cus.getXuqiuhuxingType(), "xuqiuhuxingType")); // 需求户型规格
			ratioList.add(getRatio(ro, cusNum, cus.getFtContactWay(), "ftContactWay")); // 接触方式
			ratioList.add(getRatio(ro, cusNum, cus.getPeDocumentType(), "peDocumentType")); // 证件类型
			ratioList.add(getRatio(ro, cusNum, cus.getPeDomicilePlace(), "peDomicilePlace")); // 户籍所在地
			ratioList.add(getRatio(ro, cusNum,
					cus.getPeFrameBrandId() == null ? cus.getPeFrameBrandId().toString() : "", "peFrameBrandId")); // 车驾品牌
			ratioList.add(getRatio(ro, cusNum, cus.getPeHouseholdIncome(), "peHouseholdIncome")); // 家庭年收入
			ratioList.add(getRatio(ro, cusNum, cus.getPeActivityType(), "peActivityType")); // 乐于参加的活动类型
			ratioList.add(getRatio(ro, cusNum, cus.getPeHobbyId(), "peHobbyId")); // 兴趣爱好
			ratioList.add(getRatio(ro, cusNum, cus.getPeAcademicQualifications(), "peAcademicQualifications")); // 学历
			ratioList.add(getRatio(ro, cusNum, cus.getCongshihangye(), "congshihangye_t")); // 从事行业
			ratioList.add(getRatio(ro, cusNum, cus.getCompanyXingzhi(), "companyXingzhi_t")); // 公司性质
			ratioList.add(getRatio(ro, cusNum, cus.getIsYezhu(), "isYezhu_t")); // 是否本公司业主
			ratioList.add(getRatio(ro, cusNum, cus.getRichangxinxi(), "richangxinxi_t")); // 日常信息获取途径
			ratioList.add(getRatio(ro, cusNum, cus.getIsZinv(), "isZinv_t")); // 是否有子女
			ratioList.add(getRatio(ro, cusNum, cus.getIsLaoren(), "isLaoren_t")); // 是否与老人同住
			ratioList.add(getRatio(ro, cusNum, cus.getIsYuangong(), "isYuangong_t")); // 是否员工
			ratioList.add(getRatio(ro, cusNum, cus.getReCurrentlyProperty(), "reCurrentlyProperty")); // 目前居住的物业类型
			ratioList.add(getRatio(ro, cusNum, cus.getReCurrentlyArea(), "reCurrentlyArea")); // 目前居住的面积
			ratioList.add(getRatio(ro, cusNum, cus.getReCurrentlyHouse(), "reCurrentlyHouse")); // 目前居住/办公的房子属性
			ratioList.add(getRatio(ro, cusNum, cus.getReCurrentlyStructure(), "reCurrentlyStructure")); // 目前居住的户型结构
			ratioList.add(getRatio(ro, cusNum, cus.getCoContactTime(), "coContactTime")); // 工作日联系时间
			ratioList.add(getRatio(ro, cusNum, cus.getCoInformationDays(), "coInformationDays")); // 工作日联系方式
			ratioList.add(getRatio(ro, cusNum, cus.getCoContactWeekend(), "coContactWeekend")); // 周末联系时间
			ratioList.add(getRatio(ro, cusNum, cus.getCoWeekendInformation(), "coWeekendInformation")); // 周末联系方式
			// response.success(ratioList);
		} catch (Exception e) {
			// response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(),
			// ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		// return response;
		return ratioList;
	}

	/**
	 * 计算答题率
	 * 
	 * @param ro
	 *            百分比默认100
	 * @param cusNum
	 *            回答的人数
	 * @param subjectNum
	 *            问答的问题数
	 * @param subjectName
	 *            题目
	 * @return
	 */
	private String[] getRatio(BigDecimal ro, BigDecimal cusNum, String subjectNum, String subjectName) {
		if (StringUtils.isBlank(subjectNum)) {
			String[] str = { subjectName, "0", "0" };
			return str;
		}

		DecimalFormat decimalFormat = new DecimalFormat("#.#");
		// 将题目数转为BigDecimal
		BigDecimal num = new BigDecimal(subjectNum);
		// 计算比例
		BigDecimal ratio = num.divide(cusNum, 5, BigDecimal.ROUND_HALF_UP).multiply(ro);

		String[] str = { subjectName, decimalFormat.format(ratio), subjectNum };
		return str;
	}

	@Override
	public Response<Boolean> giveUpCustomer(User user, Long customerId) {
		Response<Boolean> response = new Response<Boolean>();
		try {
			Customer customer = service.selectById(customerId);
			boolean flag = service.checkCustomerLevel(customer.getId());
			if(flag){
				response.setEntity(false);
				response.setResultMessage("客户:" + customer.getCustomerName() + "是已成交业主,您不能操作!");
				return response;
			}

			if (!customer.getUserCode().equals(user.getUserCode())) {
				UserDto dto = new UserDto();
				dto.setUserCode(customer.getUserCode());
				User customerUser = userServiceFacade.selectByDto(dto);
				if (customerUser == null) {
					response.setEntity(false);
					response.setResultMessage("经纪人为空!");
				} else {
					response.setEntity(false);
					response.setResultMessage(
							"客户:" + customer.getCustomerName() + ",所属经纪人为:" + customerUser.getUserName() + ",您不能操作!");
				}
			} else {
				// 是否存在待办事项
				ActNodeQuery actQuery = new ActNodeQuery();
				actQuery.setqType(ActDataTypeEnum.ACT_1.getNo());
				actQuery.setCustomerNameOrPhone(customer.getCustomerPhone());
				actQuery.setQueryTypeSql(" and t.END_TIME_ IS NULL ");
				List<ActNodeDataDto> actNodeList = actNodeDataService.queryActByBusinessKey(actQuery, 0, 100);
				if (actNodeList != null && actNodeList.size() > 0) {
					response.setEntity(false);
					response.setResultMessage("客户:" + customer.getCustomerName() + ",存在待办事项,请先处理!");
				} else {
					CustomerDto entity = new CustomerDto();
					entity.setId(customerId);
					entity.setGiveUpStatus(GiveUpStatusEnum.GIVEUP.getNo());
					entity.setGiveUpType(GiveUpTypeEnum.USER.getNo());
					entity.setResignTime(Calendar.getInstance().getTime());
					entity.setIsDistribution(IsDistributionEnum.UNDISTRIBUTION.getNo());
					service.update(entity);
					response.setEntity(true);
				}
			}
		} catch (Exception e) {
			logger.error("放弃客户错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<CustomerComponentDto> findGiveUpPage(CustomerComponentDto entity, Integer begin, Integer end) {
		Page<CustomerComponentDto> response = new Page<CustomerComponentDto>();
		response.setPageSize(end);
		try {
			if (null == entity || null == begin || null == end) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			// 数据权限
			if (SysConstants.openDataPermission && StringUtils.isNotBlank(entity.getResourcesCode())) {
				String dataPermission = dataPermissionService.dataPermissionCondition(entity.getPermissionUserId(),
						entity.getResourcesCode(), entity.getPrefix(), entity.getColumnName());
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					response.setErrorMsg(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					response.setSuccess(false);
					return response;
				}
				entity.setDataPermission(dataPermissionArr[1]);
			}
			Page<CustomerComponentDto> page = service.selectCustomerPage(entity, begin, end);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			page.setRows(convertCustomerComponentDto(page.getRows()));
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Boolean> getGiveUpCustomer(Long customerId, User user) {
		Response<Boolean> response = new Response<Boolean>();
		try {
			Customer customer = service.selectById(customerId);
			if (customer.getGiveUpStatus().equals("0")) {
				response.setEntity(false);
				response.setResultMessage("客户:" + customer.getCustomerName() + "为正常客户,不可认领!");
			} else {
				CustomerDto dto = new CustomerDto();
				dto.setId(customerId);
				dto.setGiveUpStatus("0");
				dto.setUserCode(user.getUserCode());
				service.update(dto);
				response.setEntity(true);
			}
		} catch (Exception e) {
			logger.error("认领客户失败:{}", e);
		}
		return response;
	}

	public List<CustomerComponentDto> convertCustomerComponentDto(List<CustomerComponentDto> dto) {
		for (CustomerComponentDto customer : dto) {
			if (!StringUtils.isEmpty(customer.getCustomerSex())) {
				customer.setCustomerSex(CustomerSexEnum.getByNo(customer.getCustomerSex()).getDes());
			}
			if (!StringUtils.isEmpty(customer.getFtContactWay())) {
				BaseCodeValue baseCodeValue = baseCodeValueService.selectById(new Long(customer.getFtContactWay()));
				if (baseCodeValue != null) {
					customer.setFtContactWay(baseCodeValue.getCodeName());
				}
			} else {
				customer.setFtContactWay("");
			}
		}
		return dto;
	}
	
	/**
	 * 修改首次接触方式 web
	 * @return
	 */
	@Override
	public AddContactWayResDto addContactWay(CustomerDto customerDto) {
		AddContactWayResDto resDto = new AddContactWayResDto();
		try {
			BaseCodeValueDto entity = new BaseCodeValueDto();
			entity.setProjectId(customerDto.getProjectId());
			entity.setCodeName("电转访");
			entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			BaseCodeValue bcv = baseCodeValueService.selectByDto(entity);
			if (bcv == null) {
				resDto.setResult("0");
				resDto.setErrorMsg("未获查询到电转访");
				return resDto;
			}
			customerDto.setFtContactWay1(bcv.getId().toString());
			customerDto.setFtContactTime1(new Date());
			resDto = addCustomerManage.addContactWay(customerDto);
		} catch (Exception e) {
			logger.error("保存电转访失败", e);
			resDto.setResult("0");
			resDto.setErrorMsg("保存电转访失败");
		}
		return resDto;
	}

	@Override
	public boolean checkCustomerLevel(Long customerId) {
		return service.checkCustomerLevel(customerId);
	}

	@Override
	public boolean checkCustomerPerfect(Long customerId) {
		return service.checkCustomerPerfect(customerId);
	}

	@Override
	public boolean changeCustomerLevel(Long customerId, String level) {
		return service.changeCustomerLevel(customerId, level);
	}



	@Override
	public Response<CommonResDTO> customerAutoGiveup(Long projectId) {
		Response<CommonResDTO> resDto = new Response<>();
		CommonResDTO commonResDTO = new CommonResDTO();

		ProjectParameterDto projectParameterDto = new ProjectParameterDto();
		projectParameterDto.setProjectId(projectId);
		projectParameterDto.setCycleType(CycleTypeEnum.giveUp.getNo());
		projectParameterDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<ProjectParameter> ppList = projectParameterService.selectListByDto(projectParameterDto);
		Map<Long, String> ppMap = new HashMap<>();
		if(null != ppList && ppList.size() > 0){
			for(ProjectParameter pp: ppList){
				ppMap.put(pp.getProjectId(), pp.getCycleValue());
			}
		}

		ProjectDto projectDto = new ProjectDto();
		projectDto.setId(projectId);
		projectDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<Project> projectList = projectService.selectListByDto(projectDto);
		if(null != projectList && projectList.size() > 0){
			for(Project project: projectList){
				int cycleValue;
				if(ppMap.get(project.getId()) != null){
					cycleValue = Integer.parseInt(ppMap.get(project.getId()));
				}else{
					//如果打开设置，则不执行job
					continue;
				}
				Calendar calendar = Calendar.getInstance();
				calendar.add(Calendar.DATE, (-1*cycleValue));

				CustomerDto customerDto = new CustomerDto();
				customerDto.setMerchantId(project.getMerchantId());
				customerDto.setProjectId(project.getId());
				customerDto.setGiveUpStatus(GiveUpStatusEnum.UN_GIVEUP.getNo());
				customerDto.setLastFollowTimeAfter(calendar.getTime());
				customerDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				//权限控制字段,借用一下.拼接一段Sql
				//含义: 非认购、签约状态下的客户
				//customerDto.setDataPermission(" AND (customer_status not in(4,5) or customer_status is null)");
				List<Customer> customerList = service.selectListByDto(customerDto);
				logger.info("项目: " + project.getProjectName() + ", 待放弃客户: " + customerList.size() + "人");
				if(null != customerList && customerList.size() > 0){
					int totalCount = 0;
					int successCount = 0;
					int failureCount = 0;
					for(Customer customer: customerList){
						boolean flag = service.checkCustomerLevel(customer.getId());
						if(flag){
							failureCount++;
							continue;
						}

						customerDto = new CustomerDto();
						customerDto.setId(customer.getId());
						customerDto.setGiveUpStatus(GiveUpStatusEnum.GIVEUP.getNo());
						customerDto.setGiveUpType(GiveUpTypeEnum.SYSTEM.getNo());
						customerDto.setResignTime(Calendar.getInstance().getTime());
						service.update(customerDto);

						FollowDto followDto = new FollowDto();
						followDto.setCustomerId(customer.getId());
						followDto.setProjectId(customer.getProjectId());
						followDto.setMerchantId(customer.getMerchantId());
						followDto.setProjectCode(project.getProjectCode());
						followDto.setFollowMode(FollowModeEnum.SYSTEMGENERATION.getNo());
						followDto.setFollowTime(Calendar.getInstance().getTime());
						followDto.setFollowType(FollowTypeEnum.TEXT.getNo());
						followDto.setFollowContent("系统放弃客户，项目：" + project.getProjectName() + ",周期：" + cycleValue + "天");
						followDto.setUserCode(customer.getUserCode());
						followDto.setAccessCode(customer.getAccessCode());
						followDto.setRemark("系统弃客");
						followDto.setCreateTime(Calendar.getInstance().getTime());
						followDto.setCreateUserId(customer.getCreateUserId());
						followDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
						followDto.setIsRead(IsReadEnum.READ.getNo());
						followDto.setIsSend(IsSendEnum.SEND.getNo());
						followService.create(followDto);
						successCount++;
					}
					String result = "总放弃人数: " + totalCount + ", 有交易客户不放弃人数: " + failureCount + ", 成功放弃: " + successCount;
					commonResDTO.setResult(result);
				}
			}
		}
		resDto.setEntity(commonResDTO);
		resDto.setSuccess(true);
		return resDto;
	}

	@Override
	public void changeCustomerPerfect(Long customerId) {
		CustomerDto customerDto = new CustomerDto();
		boolean perfectFlag = service.checkCustomerPerfect(customerId);
		customerDto.setId(customerId);
		customerDto.setIsIntentionIntact(IntentionIntactEnum.UN_PERFECT.getNo());
		if(perfectFlag){
			customerDto.setIsIntentionIntact(IntentionIntactEnum.PERFECT.getNo());
		}
		service.update(customerDto);
	}
}
